package scene_widget

import (
	"fmt"
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/cmd/fyne_settings/settings"
	"fyne.io/fyne/v2/driver/desktop"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	"net/url"
)

// MenuController 菜单控制器，管理应用程序的主菜单
// OnEditModeChanged 编辑模式改变回调
// OnSizeModeChanged 大小模式改变回调
// OnSaveClicked 保存按钮点击回调
// OnNewFileClicked 新建文件点击回调
// OnOpenFileClicked 打开文件点击回调
// OnQuitClicked 退出点击回调
type MenuController struct {
	OnEditModeChanged  func(bool)
	OnSizeModeChanged  func(bool)
	OnSaveClicked      func()
	OnSaveThisClicked  func()
	OnSaveOtherClicked func()
	OnNewFileClicked   func()
	OnOpenFileClicked  func()
	OnQuitClicked      func()

	mainMenu    *fyne.MainMenu
	editItem    *fyne.MenuItem
	sizeItem    *fyne.MenuItem
	checkedItem *fyne.MenuItem
}

// NewMenuController 创建新的菜单控制器
func NewMenuController() *MenuController {
	return &MenuController{}
}

// CreateMainMenu 创建主菜单
func (mc *MenuController) CreateMainMenu(a fyne.App, w fyne.Window) *fyne.MainMenu {
	newItem := fyne.NewMenuItem("New", nil)
	mc.checkedItem = fyne.NewMenuItem("Checked", nil)
	mc.checkedItem.Checked = true

	disabledItem := fyne.NewMenuItem("Disabled", nil)
	disabledItem.Disabled = true
	otherItem := fyne.NewMenuItem("Other", nil)
	mailItem := fyne.NewMenuItem("Mail", func() { fmt.Println("Menu New->Other->Mail") })
	mailItem.Icon = theme.MailComposeIcon()
	otherItem.ChildMenu = fyne.NewMenu("",
		fyne.NewMenuItem("Project", func() { fmt.Println("Menu New->Other->Project") }),
		mailItem,
	)
	fileItem := fyne.NewMenuItem("File", func() {
		fmt.Println("Menu New->File")
		if mc.OnNewFileClicked != nil {
			mc.OnNewFileClicked()
		}
	})
	fileItem.Icon = theme.FileIcon()
	dirItem := fyne.NewMenuItem("Directory", func() { fmt.Println("Menu New->Directory") })
	dirItem.Icon = theme.FolderIcon()
	newItem.ChildMenu = fyne.NewMenu("",
		fileItem,
		dirItem,
		otherItem,
	)

	openSettings := func() {
		settingsWindow := a.NewWindow("Fyne Settings")
		settingsWindow.SetContent(settings.NewSettings().LoadAppearanceScreen(settingsWindow))
		settingsWindow.Resize(fyne.NewSize(440, 520))
		settingsWindow.Show()
	}
	showAbout := func() {
		aboutWindow := a.NewWindow("About")
		aboutWindow.SetContent(widget.NewLabel("About Fyne Demo app..."))
		aboutWindow.Show()
	}
	aboutItem := fyne.NewMenuItem("About", showAbout)
	settingsItem := fyne.NewMenuItem("Settings", openSettings)
	settingsShortcut := &desktop.CustomShortcut{KeyName: fyne.KeyComma, Modifier: fyne.KeyModifierShortcutDefault}
	settingsItem.Shortcut = settingsShortcut
	w.Canvas().AddShortcut(settingsShortcut, func(shortcut fyne.Shortcut) {
		openSettings()
	})

	cutShortcut := &fyne.ShortcutCut{Clipboard: a.Clipboard()}

	mc.editItem = fyne.NewMenuItem("编辑Edit", nil)
	mc.editItem.Checked = true // 默认编辑模式
	mc.sizeItem = fyne.NewMenuItem("大小Size", nil)
	mc.sizeItem.Checked = false // 默认非大小模式

	cutItem := fyne.NewMenuItem("Cut", func() {
		//shortcutFocused(cutShortcut, a.Clipboard(), w.Canvas().Focused())
	})
	cutItem.Shortcut = cutShortcut
	copyShortcut := &fyne.ShortcutCopy{Clipboard: a.Clipboard()}
	copyItem := fyne.NewMenuItem("Copy", func() {
		//shortcutFocused(copyShortcut, a.Clipboard(), w.Canvas().Focused())
	})
	copyItem.Shortcut = copyShortcut
	pasteShortcut := &fyne.ShortcutPaste{Clipboard: a.Clipboard()}
	pasteItem := fyne.NewMenuItem("Paste", func() {
		//shortcutFocused(pasteShortcut, a.Clipboard(), w.Canvas().Focused())
	})
	pasteItem.Shortcut = pasteShortcut
	performFind := func() { fmt.Println("Menu Find") }
	findItem := fyne.NewMenuItem("Find", performFind)
	findItem.Shortcut = &desktop.CustomShortcut{KeyName: fyne.KeyF, Modifier: fyne.KeyModifierShortcutDefault | fyne.KeyModifierAlt | fyne.KeyModifierShift | fyne.KeyModifierControl | fyne.KeyModifierSuper}
	w.Canvas().AddShortcut(findItem.Shortcut, func(shortcut fyne.Shortcut) {
		performFind()
	})

	// 创建打开文件菜单项
	openItem := mc.createOpenMenuItem()

	// 创建文件菜单
	saveItem := mc.createSaveMenuItem()
	file := fyne.NewMenu("File", newItem, openItem, saveItem, mc.checkedItem, disabledItem)
	device := fyne.CurrentDevice()
	if !device.IsMobile() && !device.IsBrowser() {
		file.Items = append(file.Items, fyne.NewMenuItemSeparator(), settingsItem)
	}
	file.Items = append(file.Items, aboutItem)

	// 添加退出菜单项
	quitItem := fyne.NewMenuItem("退出", func() {
		// 使用fyne的应用程序退出功能
		fmt.Println("退出应用程序")
		if mc.OnQuitClicked != nil {
			mc.OnQuitClicked()
		} else {
			a.Quit()
		}
	})
	// 如果不是移动设备或浏览器，添加分隔符和退出选项
	if !device.IsMobile() && !device.IsBrowser() {
		file.Items = append(file.Items, fyne.NewMenuItemSeparator(), quitItem)
	}

	// 创建主菜单
	mc.mainMenu = fyne.NewMainMenu(
		file,
		fyne.NewMenu("Edit", mc.editItem, fyne.NewMenuItemSeparator(),
			mc.sizeItem, fyne.NewMenuItemSeparator(),
			cutItem, copyItem, pasteItem, fyne.NewMenuItemSeparator(), findItem),
		fyne.NewMenu("Help",
			fyne.NewMenuItem("Documentation", func() {
				u, _ := url.Parse("https://developer.fyne.io")
				_ = a.OpenURL(u)
			}),
			fyne.NewMenuItem("Support", func() {
			}),
			fyne.NewMenuItemSeparator(),
			fyne.NewMenuItem("Sponsor", func() {
			})),
	)

	// 设置菜单项动作
	mc.setupMenuActions()

	return mc.mainMenu
}

// createOpenMenuItem 创建打开文件菜单项
func (mc *MenuController) createOpenMenuItem() *fyne.MenuItem {
	return fyne.NewMenuItem("Open", func() {
		fmt.Println("打开文件")
		if mc.OnOpenFileClicked != nil {
			mc.OnOpenFileClicked()
		}
	})
}

// createSaveMenuItem 创建保存菜单项（带子菜单）
func (mc *MenuController) createSaveMenuItem() *fyne.MenuItem {
	// 创建"This"子菜单项
	saveThisItem := fyne.NewMenuItem("This", func() {
		fmt.Println("保存当前文件")
		if mc.OnSaveThisClicked != nil {
			mc.OnSaveThisClicked()
		}
	})
	saveThisItem.Icon = theme.DocumentSaveIcon()

	// 创建"Other"子菜单项
	saveOtherItem := fyne.NewMenuItem("Other", func() {
		fmt.Println("另存为文件")
		if mc.OnSaveOtherClicked != nil {
			mc.OnSaveOtherClicked()
		}
	})
	saveOtherItem.Icon = theme.DocumentCreateIcon()

	// 创建主保存菜单项，包含子菜单
	saveItem := fyne.NewMenuItem("Save", nil)
	saveItem.ChildMenu = fyne.NewMenu("", saveThisItem, saveOtherItem)
	//saveItem.Icon = theme.DocumentSaveIcon()

	return saveItem
}

// setupMenuActions 设置菜单项动作
func (mc *MenuController) setupMenuActions() {
	mc.checkedItem.Action = func() {
		mc.checkedItem.Checked = !mc.checkedItem.Checked
		mc.mainMenu.Refresh()
	}

	mc.editItem.Action = func() {
		mc.editItem.Checked = !mc.editItem.Checked
		// 触发编辑模式改变回调
		if mc.OnEditModeChanged != nil {
			mc.OnEditModeChanged(mc.editItem.Checked)
		}
		mc.mainMenu.Refresh()
	}

	mc.sizeItem.Action = func() {
		mc.sizeItem.Checked = !mc.sizeItem.Checked
		// 触发大小模式改变回调
		if mc.OnSizeModeChanged != nil {
			mc.OnSizeModeChanged(mc.sizeItem.Checked)
		}
		mc.mainMenu.Refresh()
	}
}

// SetEditMode 设置编辑模式（不触发回调）
func (mc *MenuController) SetEditMode(isEdit bool) {
	if mc.editItem != nil {
		mc.editItem.Checked = isEdit
		mc.mainMenu.Refresh()
	}
}

// SetEditModeInternal 内部设置编辑模式（不触发回调，用于同步）
func (mc *MenuController) SetEditModeInternal(isEdit bool) {
	if mc.editItem != nil {
		mc.editItem.Checked = isEdit
		mc.mainMenu.Refresh()
	}
}

// SetSizeMode 设置大小模式
func (mc *MenuController) SetSizeMode(isSize bool) {
	if mc.sizeItem != nil {
		mc.sizeItem.Checked = isSize
		mc.mainMenu.Refresh()
	}
}

// GetMainMenu 获取主菜单
func (mc *MenuController) GetMainMenu() *fyne.MainMenu {
	return mc.mainMenu
}
